/****************************************************************************
 * Copyright 2010 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.greatq.datastore;

import org.jiql.jdbc.Driver;
import tools.util.StringUtil;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class DatastoreDriver extends Driver {
    public static final String GREATQ_PROTOCOL = "greatq";
    static {
        try {
           DriverManager.registerDriver(new DatastoreDriver());
        } catch(Exception e){
            throw new Error("terminal error: unable to register driver");
        }
    }
    public DatastoreDriver() throws SQLException {
        super();
    }

    @Override
    public boolean acceptsURL(String url) {
        return inTheClub(url);
    }

    boolean inTheClub(String url){
        if(url == null) return false;
        try {
            final URI uri = new URI(url);
            final String greatqProtocol = uri.getScheme();
            return GREATQ_PROTOCOL.equals(greatqProtocol);
        } catch (URISyntaxException e) {
            return false;
        }
    }

    @Override
    public Connection connect(String url, Properties info) {
        try {
            final URI uri = new URI(url);
            info.put("url", uri.getRawSchemeSpecificPart());
            final String decodedUrl = StringUtil.replaceSubstring(uri.getRawSchemeSpecificPart(),"?","");
            info.put("baseUrl",decodedUrl);
            return new DatastoreConnection(info);
        } catch (URISyntaxException e) {
            throw new RuntimeException("error: unable to connect to datastore.");
        }
    }
}
